package 链表;

/**
 * 定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。
 * <p>
 * 示例:
 * <p>
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 * <p>
 * 限制：
 * 0 <= 节点个数 <= 5000
 * <p>
 * 链接：https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
 */
public class 剑指_Offer_24_反转链表 {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1, new ListNode(2, new ListNode(3, null)));
//        System.out.println(reverseList(listNode1));
        System.out.println(reverseList1(listNode1));
    }

    public static ListNode reverseList(ListNode head) {

        if (head == null || head.next == null) return head;

        ListNode node = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

    public static ListNode reverseList1(ListNode head) {
        if (head == null) return null;

        ListNode newNode = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newNode ;
            newNode = head;
            head = tmp;
        }

        return newNode;
    }
}
